﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CarouselView.Converts
{
    public class WebViewSourceConverter: IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null) return null;

            string src = value.ToString();
            if (!src.ToLower().Contains("http") && !src.ToLower().Contains("https"))
            {
                using (FileStream fileStream = new FileStream(src, FileMode.Open))
                {
                    byte[] bData = new byte[fileStream.Length];
                    //设置流当前位置为文件开始位置
                    fileStream.Seek(0, SeekOrigin.Begin);

                    //将文件的内容存到字节数组中（缓存）
                    fileStream.Read(bData, 0, bData.Length);
                    //string result = System.Text.Encoding.UTF8.GetString(bData);
                    //Console.WriteLine(result);
                    if (fileStream != null)
                    {
                        //清除此流的缓冲区，使得所有缓冲的数据都写入到文件中
                        fileStream.Flush();
                        fileStream.Close();
                    }

                    using (MemoryStream mstream = new MemoryStream(bData))
                    {
                        src = $"data:image/jpg;base64,{System.Convert.ToBase64String(mstream.ToArray())}";
                    }
                }
            }

            return new HtmlWebViewSource
            {
                Html = $@"<HTML><BODY style='background-color:black;text-align:center;'><img src='{src}' style='max-width:100%;' /></BODY></HTML>"
            };
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
